import React, { useEffect, useState, useRef } from 'react'
import { connect, useDispatch } from "react-redux";
import dayjs from 'dayjs';
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction';
// import timelinePlugin from '@fullcalendar/timeline';
import './index.scss'
import { View, Text } from '@tarojs/components'
import Taro, { Component } from '@tarojs/taro'


function App(props) {
    useEffect(() => { }, [])
    const [scrollTime, setScrollTime] = useState(dayjs().format('HH:mm:ss'));
    const [currentTime, setCurrentTime] = useState<Date>(new Date());
    const [eventMirror, setEventMirror] = useState({});
    const [oldDateStr, setOldDateStr] = useState('');
    const [oldEndDateStr, setOldEndDateStr] = useState('');

    const {
        datalist,
        onClickItem,
        date
    } = props
    console.log(datalist, 'datalist');

    const scheduleList = [];
    datalist &&
        datalist.forEach((item: any) => {
            item.color = item.beCourse == 1 ? 'rgb(255,247,242)' : 'rgb(242,250,255)'
            item.textColor = item.beCourse == 1 ? 'rgb(255,102,0)' : 'rgb(0,134,223)'
            item.title = item.scheduleTitle
            item.class = item.className
            item.times = parseInt(new Date(item.scheduleDate + ' ' + item.endTime) - new Date(item.scheduleDate + ' ' + item.startTime)) / 1000 / 60
            item.startTime1 = item.startTime
            item.endTime1 = item.endTime
            if (item.beAllDay == '1') return;
            scheduleList.push(item);
            return scheduleList;
        })
    //点击日程事件
    const eventClick = (eventInfo: any) => {
        // console.log(eventInfo.event._def,'eventInfo.event._def.extendedProps');
        // console.log(eventInfo,'eventInfo.event._def.extendedProps');
        let start = eventInfo.event._def.extendedProps.startTime1
        let end = eventInfo.event._def.extendedProps.endTime1
        // if (eventInfo.event.display === 'background') {
        //     Taro.showToast({
        //         title:'21212',
        //         icon:'none',
        //         duration:2000
        //     })
        //     let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + start + '&end=' + end
        //     Taro.navigateTo({
        //         url
        //     })
        // } else {
        onClickItem(eventInfo.event._def.extendedProps)
        // }
    }

    const renderEventContent = (eventInfo) => {
        let data = eventInfo.event._def.extendedProps;

        return (
            <View className='schedule-container'>
                <View className={data.beCourse == '0' ? 'schedule-title' : 'schedule-title schedule-title-course'}>{data.beCourse == '0' ? data.scheduleTitle : data.scheduleContent}
                    {data.beCourse == '1' ?
                        <View className='schedule-course'><Text className='schedule-course-text'>{data.scheduleMark}课</Text></View> : ''
                    }</View>
                {
                    data.times < 45 ? '' : <View className={data.beCourse == '0' ? 'schedule-location' : 'schedule-location schedule-location-course'}>
                        <Text className='schedule-content' style={{ marginRight: data.scheduleContent || data.class ? '' : '0' }}>{data.beCourse == '0' ? data.scheduleContent : data.class}</Text>
                        {/* {data.beCourse == '1' ? <Text className='schedule-content'>{data.class}</Text> : ''} */}
                        <Text className='address'>{data.scheduleLocation ? (data.scheduleContent || data.class ? '(' : '') + data.scheduleLocation + (data.scheduleContent || data.class ? ')' : '') : ''}</Text>
                    </View>
                }
            </View>
        )
    }

    const calendarRef = useRef(null);
    useEffect(() => {
        const calendarApi = calendarRef.current.getApi();
        let startTime = '00:00:00';
        //日期
        let day = dayjs().format('YYYY-MM-DD')
        //计算当前时间橙色横线所在时间
        let next = calendarApi.el.childNodes[0].childNodes[2].childNodes[1].childNodes[1];
        next.click();
        // if (day == date) {
        startTime = dayjs().format('HH:mm:ss')
        setTimeout(() => {
            let today = calendarApi.el.childNodes[0].childNodes[2].childNodes[0];
            today.click();
            const startTime1 = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate(), currentTime.getHours(), Math.floor(currentTime.getMinutes() / 30) * 30);

            setCurrentTime(startTime1);
            let timeLine = document.getElementsByClassName('fc-timegrid-now-indicator-arrow')
            // console.log(timeLine, 'timeLine');
            for (let i = 0; i < timeLine.length; i++) {
                timeLine[i].innerHTML = dayjs().format('HH:mm')
            }
        }, 300);
        // }
        calendarApi.scrollToTime(startTime);
    }, [date]);
    const selectOverlap = (event) => {
        // console.log(event, 'event');

        return event.rendering === 'background';
    }

    //拖动
    const eventAllow = (dropInfo, draggedEvent) => {
        console.log(dropInfo, draggedEvent, 'event');
        if (draggedEvent.id === '999') {
            return dropInfo.start < new Date(2016, 0, 1); // a boolean
        }
        else {
            return true;
        }
    }
    const handleSelect = (arg: DateSelectArg) => {
        let calendarApi = arg.view.calendar;
        let events = calendarApi.getEvents();
        for (let i = 0; i < events.length; i++) {
            let title = events[i]._def.title;
            if (title == '再次点击新建日程') {
                events[i].remove();
            }
        }
        const { start, end } = arg;
        //选择时间段添加新的日程
        const newEventBtnEl = document.createElement('View');
        newEventBtnEl.innerHTML = '再次点击新建日程';
        newEventBtnEl.style.position = 'absolute';
        newEventBtnEl.style.top = '50%';
        newEventBtnEl.style.left = '50%';
        newEventBtnEl.style.transform = 'translate(-50%, -50%)';
        newEventBtnEl.style.backgroundColor = '#41be5e';
        newEventBtnEl.style.padding = '8px';
        newEventBtnEl.style.borderRadius = '8px';
        newEventBtnEl.style.fontSize = '16px';
        newEventBtnEl.style.color = '#fff';
        newEventBtnEl.style.cursor = 'pointer';
        newEventBtnEl.style.zIndex = '99'
        newEventBtnEl.style.width = '100%'
        newEventBtnEl.style.height = '98%'
        // 添加一个特殊的元素
        let mirror = document.querySelector('.fc-event-mirror');
        mirror.appendChild(newEventBtnEl);
        // 添加新建事件的点击事件
        newEventBtnEl.addEventListener('click', () => {
            setTimeout(() => {
                if (mirror) {
                    mirror.remove();
                }
            }, 1000);
            // TODO: 进入新建日程页面
            let url = '/pages/scheduleApp/createSchedule/index?startDate=' + date + '&start=' + dayjs(start).format('HH:mm:ss') + '&end=' + dayjs(end).format('HH:mm:ss')
            Taro.navigateTo({
                url
            })
        })

        // 添加点击其他地方隐藏区域的事件
        window.addEventListener('click', (e) => {
            if (mirror) {
                mirror.remove();
            }

        })
    }
    const handleSelect1 = (arg: DateSelectArg) => {
        setOldDateStr(arg.startStr);
        setOldEndDateStr(arg.endStr);
        let calendarApi = arg.view.calendar;
        let events = calendarApi.getEvents();
        for (let i = 0; i < events.length; i++) {
            let title = events[i]._def.title;
            if (title == '再次点击新建日程') {
                events[i].remove();
            }
        }
        const { start, end } = arg;
        const newEvent = {
            className: 'new-event',
            title: '再次点击新建日程',
            start: start,
            end: end,
            display: 'background',
            color: '#41be5e',
            extendedProps: {
                "scheduleTitle": "再次点击新建日程",
                "beAllDay": "0",
                "repeatTime": "0",
                "beSkipHolidays": "0",
                "beCourse": "0",
                "functionLinkInfoList": [],
                "inviteCount": "0",
                "markDone": "0",
                "beExternal": "0",
                "beMeeting": "0",
                "startTime1": dayjs(start).format('HH:mm'),
                "endTime1": dayjs(end).format('HH:mm'),
                "isCreate": 1
            }
        };
        setTimeout(() => {
            calendarApi.addEvent(newEvent);
        }, 100);
        calendarRef.current.getApi().unselect();
    }

    const handleDateClick = (info) => {
        const calendarApi = info.view.calendar;
        const startTime = info.date.getTime();
        const endTime = new Date(startTime + 60 * 60 * 1000).getTime();
        const events = calendarApi.getEvents();
        setOldDateStr(info.dateStr);
        setOldEndDateStr(dayjs(endTime).format('YYYY-MM-DDTHH:mm:ssZ'));
        if (oldDateStr == info.dateStr || (oldDateStr < info.dateStr && info.dateStr < oldEndDateStr)) return;
        for (let i = 0; i < events.length; i++) {
            const start = events[i].start.getTime();
            const end = events[i].end ? events[i].end.getTime() : start;
            let title = events[i]._def.title;
            if (title == '再次点击新建日程') {
                events[i].remove();
            }
        }

        const newEvent = {
            className: 'new-event',
            title: '再次点击新建日程',
            start: info.date,
            end: new Date(startTime + 60 * 60 * 1000),
            display: 'background',
            color: '#41be5e',
            extendedProps: {
                "scheduleTitle": "再次点击新建日程",
                "beAllDay": "0",
                "repeatTime": "0",
                "beSkipHolidays": "0",
                "beCourse": "0",
                "functionLinkInfoList": [],
                "inviteCount": "0",
                "markDone": "0",
                "beExternal": "0",
                "beMeeting": "0",
                "startTime1": dayjs(startTime).format('HH:mm'),
                "endTime1": dayjs(endTime).format('HH:mm'),
                "isCreate": 1
            }
        };
        setTimeout(() => {
            calendarApi.addEvent(newEvent);
        }, 100);
        // calendarApi.deleteEvent(newEvent);
    };

    let day = dayjs().format('YYYY-MM-DD')

    return (
        <View className='schedule-grid'>
            <FullCalendar
                plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
                initialView="timeGridDay" // 初始化在week维度
                // initialView="dayGridMonth" // 初始化在week维度
                selectable={true}
                select={handleSelect1}
                selectOverlap={selectOverlap}
                selectMirror={true}
                selectMinDistance={60}
                dateClick={handleDateClick}
                editable={false}//用来设置日历中的日程是否可以编辑. 可编辑是指可以移动, 改变大小等
                eventStartEditable={false}
                eventResizableFromStart={false}
                locale="zh-cn"
                // locale="UTC"
                allDaySlot={false} // 不显示all-day
                // buttonText={{ today: '今天', month: '月', week: '周', day: '天' }}
                // headerToolbar={false} //头部按钮
                firstDay={1} // 从周六开始
                // scrollTime={'06:00:00'} // 初始滚动条滚动到的时间位置：6点
                slotLabelFormat={{ hour: '2-digit', minute: '2-digit', meridiem: false, hour12: false }} // 左侧时间格式
                defaultTimedEventDuration={'01:00:00'} // 当没有设置endTime时的持续时间为1个小时
                // displayEventEnd
                eventClick={eventClick}
                eventSources={[scheduleList]} // 数据源
                height={'100%'}
                eventContent={renderEventContent}
                // dateClick={dateClick}
                slotDuration={'00:60:00'}
                // timeZone="zh-cn"
                // scrollTime={day == date ? scrollTime : '00:00:00'}
                scrollTime={scrollTime}
                scrollTimeReset={true}
                // displayEventTime={false}
                ref={calendarRef}
                dragScroll={false}
                eventAllow={eventAllow}//拖动事件
                // nowIndicator={day == date ? true : false}//时间线
                nowIndicator={true}//时间线
                now={currentTime}//当前时间
                unselectAuto={false}

            />
        </View>
    )
}

const mainProps = ({ commonData }) => {
    return {
        userInfo: commonData.userInfo,
    }
}

export default connect(mainProps)(App)
